Component({
  options: {
    multipleSlots: true // 在组件定义时的选项中启用多slot支持
  },
  properties: {
    value: { // 数据
      type: Array,
      value: '',
      observer(newVal,oldVal){
        let isFirst = !(Array.isArray(oldVal) && oldVal.length > 0);
        let startIndex = isFirst ? 0 : oldVal.length;
        this.data.list = this.data.list.concat(this.cloneData(newVal.slice(startIndex)));
        if(isFirst){
          this.initFirst();
        }else{
          this.computedHeight();
        }
      }
    },
  },
  lifetimes:{
    ready(){}
  },
  data: {
    list:[],
    leftList:[],
    rightList:[],
    width:0,
    index:1,
    leftHeight:0,
    rightHeight:0
  },
  methods: {
    // 复制而不是引用对象和数组
		cloneData(data) {
			return JSON.parse(JSON.stringify(data));
		},
    //初始化第一条数据
    initFirst(){
      let leftList=[];
      leftList.push(this.data.list[0]);
      this.setData({
        leftList
      })
      this.createSelectorQuery().select('#waterfall-left').boundingClientRect((res) => {
        this.setData({
          width:res.width
        })
      }).exec();
    },
    //获取高度
    getHeight(elementId){
      this.createSelectorQuery().select(elementId).boundingClientRect((res) => {
        if(!res) return;
        if(elementId == "#waterfall-left"){
          this.data.leftHeight = res.height;
        }else if(elementId == "#waterfall-right"){
          this.data.rightHeight = res.height;
        }
        this.computedHeight();
      }).exec();
    },
    //计算高度加载数据
    computedHeight(){
      console.log(this.data.leftHeight,this.data.rightHeight)
      let allList = this.data.list;
      if(this.data.index >= allList.length) return;
      if(this.data.leftHeight <= this.data.rightHeight){
        let leftList = this.data.leftList;
        leftList.push(allList[this.data.index])
        this.setData({
          leftList
        })
      }else{
        let rightList = this.data.rightList;
        rightList.push(allList[this.data.index])
        this.setData({
          rightList
        })
      }
      this.data.index += 1;
    },
    //加载左侧图片
    loadLeftImg(e){
      let index = e.currentTarget.dataset.index;
      let height = parseInt(e.detail.height * this.data.width / e.detail.width);
      let param = 'leftList['+ index +'].height';
      this.setData({
        [param]: height
      })
      this.getHeight('#waterfall-left');
    },
    //在家右侧图片
    loadRightImg(e){
      let index = e.currentTarget.dataset.index;
      let height = parseInt(e.detail.height * this.data.width / e.detail.width);
      let param = 'rightList['+ index +'].height';
      this.setData({
        [param]: height
      })
      this.getHeight('#waterfall-right');
    }
  }
})